<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'
import {queryYearRangeTotalCO2} from "@/api/carbon-manage/data";

require('echarts/theme/macarons') // echarts theme

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    curYear: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      chart: null,
      years: [],
      carbonData: []
    }
  },
  watch: {
    curYear(newVal, oldVal) {
      queryYearRangeTotalCO2({begin: newVal[0], end: newVal[1]}).then(res => {
        console.log(res);
        this.years = res.data.map(item => {
          return item.year + '年';
        });
        this.carbonData = res.data.map(item => {
          return {value: item.carbonEmission, name: item.year + '年'};
        });

        this.initChart();
      })
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    });

    queryYearRangeTotalCO2({begin: this.curYear[0], end: this.curYear[1]}).then(res => {
      this.years = res.data.map(item => {
        return item.year + '年';
      });
      this.carbonData = res.data.map(item => {
        return {value: item.carbonEmission, name: item.year + '年'};
      });

      this.$nextTick(() => {
        this.initChart()
      });
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: this.years
        },
        series: [
          {
            name: '企业年度二氧化碳排放总量',
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '38%'],
            data: this.carbonData,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
